package cn.ekuma.security.util;

import java.util.List;

import cn.ekuma.security.bean.I_GroupPermission;
import cn.ekuma.security.bean.I_Permission;
import cn.ekuma.security.impl.GroupPermission;
import cn.ekuma.security.impl.TempPermission;

public class SecurityUtil {

	public static int getPermissionLevel(I_Permission p){
		int i=p.getId();
		if((i&I_GroupPermission.GROUP_FORE_FILTER)>0)
			return 4;
		else if((i&I_GroupPermission.GROUP_THREE_FILTER)>0)
			return 3;
		else if((i&I_GroupPermission.GROUP_TWO_FILTER)>0)
			return 2;
		return 1;
	}
	
	public static int[] getLevelValue(I_Permission p){
		int[] value=new int[4];
		value[0]=I_GroupPermission.GROUP_ONE&p.getId();
		value[1]=I_GroupPermission.GROUP_TWO&p.getId();
		value[2]=I_GroupPermission.GROUP_THREE&p.getId();
		value[3]=p.getId();
		return value;
	}
	
	public static int getLevelValue(I_Permission p,int level){
		if(level==1)
			return I_GroupPermission.GROUP_ONE&p.getId();
		if(level==2)
			return I_GroupPermission.GROUP_TWO&p.getId();
		if(level==3)
			return I_GroupPermission.GROUP_THREE&p.getId();
		return p.getId();
	}
	
	public static I_GroupPermission getRoot(List<I_Permission> ps){
		I_GroupPermission root=new GroupPermission(null,null);
		for(I_Permission p:ps)
			addPermissionToGroup(root,p);
		return root;
	}
	

	private static void addPermissionToGroup(I_GroupPermission parent,
			I_Permission p) {
		int permissionLevel=getPermissionLevel(p);
		int value=getLevelValue(p,parent.getLevel());
		I_GroupPermission group=parent.getChildById(value);
		if(permissionLevel==parent.getLevel()+1){
			if(group==null){
				group=new GroupPermission(parent,p,parent.getLevel()+1);
				parent.addChildPermission(group);
			}else{
				group.setPermission(p);
			}	
		}else{
			if(group==null){
				group=new GroupPermission(parent,new TempPermission(value),parent.getLevel()+1);
				parent.addChildPermission(group);
			}
			addPermissionToGroup(group,p);
		}
	}
	
}
